﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Queries.Accounts.GetOne;

public class GetOneAccountsQueryHandler : IRequestHandler<GetOneAccountsQueryRequest, GetOneAccountsQueryResponse>
{
    private readonly IAccountRepository _accountRepository;
    private readonly IMapper _mapper;

    public GetOneAccountsQueryHandler(IMapper mapper, IAccountRepository accountRepository)
    {
        _mapper = mapper;
        _accountRepository = accountRepository;
    }

    public async Task<GetOneAccountsQueryResponse> Handle(GetOneAccountsQueryRequest request, CancellationToken cancellationToken)
    {
        var account = await _accountRepository.FirstOrDefaultAsync(x => x.Id == request.AccountId, cancellationToken);
        if (account == null) throw new NotFoundException($"Аккаунт с id '{request.AccountId}' не найден");

        return _mapper.Map<GetOneAccountsQueryResponse>(account);
    }
}